package com.shujia.hivefun.udtf;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

import java.util.ArrayList;


/**
 *   进入的一行：   a,1,2,3,4,5,6,7,8,9,10,11,12
 *   出来的是：
 *              a  0时  1
 *              a  2时  2
 *              a  4时  3
 *              ...
 */
public class HiveUDTF2 extends GenericUDTF {
    @Override
    public StructObjectInspector initialize(StructObjectInspector argOIs) throws UDFArgumentException {
        ArrayList<String> filedNames = new ArrayList<String>();
        ArrayList<ObjectInspector> fieldObj = new ArrayList<ObjectInspector>();
        filedNames.add("id");
        fieldObj.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        filedNames.add("hours");
        fieldObj.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        filedNames.add("value");
        fieldObj.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        return ObjectInspectorFactory.getStandardStructObjectInspector(filedNames, fieldObj);
    }

    //a,1,2,3,4,5,6,7,8,9,10,11,12
    public void process(Object[] objects) throws HiveException {
        int hours = 0;
        Object id = objects[0];
        for(int i=1;i<objects.length;i++){
            String line = id+","+hours+"时"+","+objects[i].toString();
            String[] cols = line.split(",");
            forward(cols);
            hours = hours + 2;
        }
    }

    public void close() throws HiveException {

    }
}
